/*
 * vim: ts=4 sw=4 fdm=marker noet tw=78 ai
 * %%LICENSE%%
 */
#include <sys/cdefs.h>
#ifdef __FBSDID
__FBSDID("$Coar$");
#endif

#include <sys/types.h>

#include <assert.h>
#include <err.h>

#include <lber_types.h>
#include <ldap.h>

#include "extern.h"
#include "search.h"
#include "fetch.h"

int
lde_fetch_operational(runtime_t *ctx, char *type, lde_found_cb fn)
{
	int 			  retval; // Return value
	int				  entrycnt; // Entry count
	LDAPMessage 	 *resp = NULL; // Search response from server
	LDAPMessage 	 *cur; // Current entry
	struct berval	**vals; // Value array in BER values
	size_t			  i; // Iterator for value array

	assert(ctx != NULL);
	assert(ctx->ld != NULL);
	TRACEIN(ctx, __func__, "ctx->ld=%p", ctx->ld);

	retval = lde_search_operational(ctx, type, &resp);
	if( retval != LDAP_SUCCESS )
		goto out;

	if( (entrycnt = ldap_count_entries(ctx->ld, resp)) > 0 )
	{
		LOG(ctx, 1, "Processing %i entries", entrycnt);
		for(
				cur = ldap_first_entry(ctx->ld, resp);
				cur != NULL;
				cur = ldap_next_entry(ctx->ld, cur)
		   )
		{
			vals = ldap_get_values_len(ctx->ld, cur, type);
			for( i=0; vals[i] != NULL; i++ )
			{
				if( vals[i]->bv_val != NULL )
					fn(ctx, vals[i]->bv_val);
				else
					warnx("Attribute with NULL value skipped.");
			}// value iterator
			ldap_value_free_len(vals);
		}// entry iterator
	}
	else
	{
		warnx("No entries received. Check server ACL");
		retval = LDAP_OPERATIONS_ERROR;
	}

out:
	if( resp )
		ldap_msgfree(resp);
	TRACEOUT(ctx, __func__, "Returning 0x%02x", retval);
	return (retval);

}
